package com.want.service;

import com.want.entity.Comment;
import com.want.entity.CommentPoll;
import com.want.model.dto.Result;
import com.want.model.dto.ResultUtil;
import com.want.repository.CommentPollRepository;
import com.want.repository.CommentRepository;
import com.want.req.comment.dto.CommentCrtReqDto;
import com.want.req.comment.dto.CommentPollReqDto;
import com.want.util.MyBeanUtil;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;
import java.util.Objects;

/**
 * @author WangZhiJian
 * @since 2021/12/1
 */
@Service
public class CommentService {

    @Resource
    private CommentRepository commentRepository;
    @Resource
    private CommentPollRepository commentPollRepository;

    public Mono<Result<Integer>> saveComment(CommentCrtReqDto commentCrtReqDto){
        Comment comment = MyBeanUtil.copyProperties(commentCrtReqDto, Comment.class);
        return commentRepository.save(comment)
                .map(Comment::getId)
                .map(ResultUtil::ofSuccess);
    }

    public Mono<Result<Integer>> pollComment(CommentPollReqDto commentPollReqDto){
        return commentPollRepository.findByUserIdCAndCommentId(commentPollReqDto.getUserId(),commentPollReqDto.getCommentId())
                .flatMap(commentPoll -> {
                    if(Objects.equals(commentPoll.getIsPositive(),commentPollReqDto.getIsPositive())){
                        return commentPollRepository.deleteById(commentPoll.getId())
                                .then(Mono.defer(() -> Mono.just(ResultUtil.ofSuccess(commentPoll.getId()))));
                    }
                    return commentPollRepository.deleteById(commentPoll.getId())
                            .then(Mono.defer(() -> Mono.just(commentPollReqDto)
                                    .map(dto -> MyBeanUtil.copyProperties(dto, CommentPoll.class))
                                    .flatMap(commentPollRepository::save)
                                    .map(CommentPoll::getId)
                                    .map(ResultUtil::ofSuccess))
                            );
                }).switchIfEmpty(Mono.defer(() -> Mono.just(commentPollReqDto)
                    .map(dto -> MyBeanUtil.copyProperties(dto, CommentPoll.class))
                    .flatMap(commentPollRepository::save)
                    .map(CommentPoll::getId)
                    .map(ResultUtil::ofSuccess))
                );
    }
}
